//
//  SAPayDocumentsDetailVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/8/27.
//

#import "SAPayDocumentsDetailVC.h"
#import "SAReceiveDetailAPI.h"
#import "SAPayDocumentsDetailModel.h"

#import "SAReceiveReceivePayAPI.h"
#import "SAReceiveQueryStatusAPI.h"
#import "ScanHelper.h"
#import "GFAlertView.h"

@interface SAPayDocumentsDetailVC ()<HTTPAPIDelegate>

@property (nonatomic, strong) UILabel *memberLab;
@property (nonatomic, strong) UILabel *storeNameLab;
@property (nonatomic, strong) UILabel *moneyLab;
@property (nonatomic, strong) UILabel *payTypeLab;
@property (nonatomic, strong) UILabel *orderTypeLab;
@property (nonatomic, strong) UILabel *dateLab;
@property (nonatomic, strong) NSString *orderId;
@property (nonatomic, strong) SAReceiveDetailAPI *receiveDetailAPI;
@property (nonatomic, strong) SAPayDocumentsDetailModel *payModel;
@property (nonatomic, strong) UIButton *payBtn;

@property (nonatomic, strong) NSString *receiveOrderId;
@property (nonatomic, strong) NSString *receiveOrderNo;
@property (nonatomic, strong) SAReceiveReceivePayAPI *receiveReceivePayAPI;
@property (nonatomic, strong) SAReceiveQueryStatusAPI *receiveQueryStatusAPI;
@property (nonatomic, assign) BOOL isPolling;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int count;

@end

@implementation SAPayDocumentsDetailVC

-(instancetype)initWithOrderId:(NSString *)orderId {
    if (self = [super init]) {
        self.orderId = orderId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.receiveDetailAPI == api) {
        self.payModel = [SAPayDocumentsDetailModel mj_objectWithKeyValues:data[@"data"]];
        self.receiveOrderId = self.payModel.receiveOrderId;
        self.receiveOrderNo = self.payModel.receiveOrderNo;
        if (self.payModel.memberName.length > 0) {
            self.memberLab.text = [NSString stringWithFormat:@"%@(%@)",self.payModel.memberName,self.payModel.memberMobile];
        }else {
            self.memberLab.text = @"散客";
        }
        self.storeNameLab.text = [NSString stringWithFormat:@"%@(%@)",self.payModel.empName,self.payModel.empMobile];
        self.moneyLab.text = [NSString stringWithFormat:@"%0.2f",[self.payModel.amount floatValue] / 100.f];
        self.dateLab.text = self.payModel.createTime;
        
        NSMutableArray *payMarr = [NSMutableArray array];
        for (SASalePayListModel *list in self.payModel.payList) {
            if ([list.payType isEqualToString:@"1"]) {
                NSString *str = [NSString stringWithFormat:@"现金(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }else if ([list.payType isEqualToString:@"2"]) {
                NSString *str = [NSString stringWithFormat:@"刷卡(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }else if ([list.payType isEqualToString:@"4"]) {
                NSString *str = [NSString stringWithFormat:@"微信(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }else if ([list.payType isEqualToString:@"5"]) {
                NSString *str = [NSString stringWithFormat:@"支付宝(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }else if ([list.payType isEqualToString:@"6"]) {
                NSString *str = [NSString stringWithFormat:@"余额(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }else if ([list.payType isEqualToString:@"7"]) {
                NSString *str = [NSString stringWithFormat:@"扫码收款(%0.2lf)",[list.payPrice doubleValue]/100.f];
                [payMarr addObject:str];
            }
        }
        self.payTypeLab.text = [payMarr componentsJoinedByString:@" "];
        
        BOOL isHidden = YES;
        switch (self.payModel.status) {
            case 0:
                self.orderTypeLab.text = @"待支付";
                isHidden = NO;
                break;
            case 2:
                self.orderTypeLab.text = @"已支付";
                break;
            case 4:
                self.orderTypeLab.text = @"已取消";
                break;
            case 6:
                self.orderTypeLab.text = @"部分退";
                break;
            case 8:
                self.orderTypeLab.text = @"已退款";
                break;
            default:
                self.orderTypeLab.text = @"";
                break;
        }
        self.payBtn.hidden = isHidden;
    }else if (self.receiveReceivePayAPI == api) {
        NSInteger status = [data[@"status"] integerValue];
        if (status == 2) {
            [self.receiveDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
            [Prompt popPromptViewWithMsg:@"支付成功" duration:2];
        }else if (status == 0) {
            self.isPolling = YES;
            self.count = 31;
            [HDHubView loadingMessage:@"正在查询支付状态..."];
            self.receiveQueryStatusAPI.orderNo = self.receiveOrderNo;
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
        }else {
            [self tipAlertView:@"支付失败"];
        }
    }else if (self.receiveQueryStatusAPI == api) {
        if (self.isPolling == YES) {
            NSInteger status = [data[@"data"][@"status"] integerValue];
            if (status == 2) {
                self.isPolling = NO;
                [self.timer invalidate];
                self.timer = nil;
                [HDHubView dismissLoading];
                [self.receiveDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
                [Prompt popPromptViewWithMsg:@"支付成功" duration:2];
            }else if (status == 6 || status == 8) {
                self.isPolling = NO;
                [self.timer invalidate];
                self.timer = nil;
                [HDHubView dismissLoading];
                [self tipAlertView:@"支付失败"];
            }
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.receiveQueryStatusAPI == api) {
        if (self.isPolling == YES) {
            self.isPolling = NO;
            [self.timer invalidate];
            self.timer = nil;
            [HDHubView dismissLoading];
            NSDictionary *dic = error.userInfo;
            NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [self tipAlertView:msg];
        }
    }else if (self.receiveReceivePayAPI == api) {
        NSDictionary *dic = error.userInfo;
        NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        [self tipAlertView:msg];
    }
}

#pragma mark - event
-(void)clickedPayBtn {
    [self scanQrcode];
}

-(void)scanQrcode {
    WeakSelf
    __block NSString *receiveOrderId = self.receiveOrderId;
    __block NSString *receiveOrderNo = self.receiveOrderNo;
    [self.navigationController pushViewController:[[ScanHelper shareInstance] ScanVCWithStyle:weixinStyle qrResultCallBack:^(id result) {
        weakSelf.receiveReceivePayAPI.authCode = result;
        weakSelf.receiveReceivePayAPI.receiveOrderId = receiveOrderId;
        weakSelf.receiveReceivePayAPI.receiveOrderNo = receiveOrderNo;
        [weakSelf.receiveReceivePayAPI sendRequestToServerWithActivityViewAndMask:POST];
        [self.navigationController popViewControllerAnimated:NO];
    }] animated:YES];
}

- (void)timerFired {
    if (self.count != 1) {
        self.count -= 1;
        [self.receiveQueryStatusAPI sendRequestToServerWithType:POST];
    } else {
        self.isPolling = NO;
        // 停掉定时器
        [self.timer invalidate];
        self.timer = nil;
        [HDHubView dismissLoading];
    }
}

-(void)tipAlertView:(NSString *)msg {
    GFAlertView *alertView = [GFAlertView alertViewWithMsg:@"提示" detailMsg:msg knowBtnBlock:^(UIButton *knowBtn) {
        [knowBtn setTitle:@"重试" forState:UIControlStateNormal];
        [knowBtn addTarget:self action:@selector(continuePay) forControlEvents:UIControlEventTouchUpInside];
    }];
    [alertView showWithAnimation];
}

-(void)continuePay {
    [self scanQrcode];
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"单据详情"];
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScaleNum(270))];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    
    NSArray *arr = @[@"会员", @"店员", @"金额", @"支付方式", @"订单状态", @"日期"];
    for (int i = 0; i < arr.count; i++) {
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(kScaleNum(20), kScaleNum(StatusHeight + 45 * i), kScaleNum(70), kScaleNum(45))];
        titleLab.text = arr[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kBlackColor;
        [self.view addSubview:titleLab];
        
        UILabel *contentLab = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - kScaleNum(285), kScaleNum(StatusHeight + 45 * i), kScaleNum(265), kScaleNum(45))];
        contentLab.font = kFont(15);
        contentLab.textAlignment = NSTextAlignmentRight;
        contentLab.textColor = kBlackColor;
        [self.view addSubview:contentLab];
        
        if (i == 0) {
            self.memberLab = contentLab;
        }else if (i == 1) {
            self.storeNameLab = contentLab;
        }else if (i == 2) {
            self.moneyLab = contentLab;
        }else if (i == 3) {
            self.payTypeLab = contentLab;
        }else if (i == 4) {
            self.orderTypeLab = contentLab;
        }else if (i == 5) {
            self.dateLab = contentLab;
        }
        if (i < 5) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(kScaleNum(20), kScaleNum(StatusHeight + 45 * i + 44.5), kScreenWidth - kScaleNum(40), kScaleNum(0.5))];
            line.backgroundColor = kBgColor;
            [self.view addSubview:line];
        }
    }
    
    UIButton *payBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    payBtn.frame = CGRectMake(0, kScreenHeight - kScaleNum(35) - SafeFooterHeight, kScreenWidth, kScaleNum(35) + SafeFooterHeight);
    payBtn.backgroundColor = kPinkColor;
    [payBtn setTitle:@"去支付" forState:UIControlStateNormal];
    payBtn.titleLabel.font = kBFont(18);
    [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [payBtn addTarget:self action:@selector(clickedPayBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:payBtn];
    payBtn.hidden = YES;
    self.payBtn = payBtn;
    
    self.receiveDetailAPI.orderId = self.orderId;
    [self.receiveDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
}

-(SAReceiveDetailAPI *)receiveDetailAPI {
    if (!_receiveDetailAPI) {
        _receiveDetailAPI = [SAReceiveDetailAPI apiWithDelegate:self];
    }
    return _receiveDetailAPI;
}

-(SAReceiveReceivePayAPI *)receiveReceivePayAPI {
    if (!_receiveReceivePayAPI) {
        _receiveReceivePayAPI = [SAReceiveReceivePayAPI apiWithDelegate:self];
        _receiveReceivePayAPI.isPromptErrorMessage = NO;
    }
    return _receiveReceivePayAPI;
}

-(SAReceiveQueryStatusAPI *)receiveQueryStatusAPI {
    if (!_receiveQueryStatusAPI) {
        _receiveQueryStatusAPI = [SAReceiveQueryStatusAPI apiWithDelegate:self];
        _receiveQueryStatusAPI.isPromptErrorMessage = NO;
    }
    return _receiveQueryStatusAPI;
}

@end

